package com.quantgroup.data.saastest.config;

import cn.hutool.core.util.StrUtil;
import com.quantgroup.saas.dynamicdatasources.SaasParameter;
import com.quantgroup.saas.dynamicdatasources.TenantVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 租户过滤器
 * @author yangjinhua
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class TenantFilter implements Filter {

    public TenantFilter() {}

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String tid = null;
        try {
            tid = request.getHeader("tid");
            if (StrUtil.isEmpty(tid)) {
                tid = request.getParameter("tid");
            }
            TenantVo tenantVo = new TenantVo();
            tenantVo.setTenantPrefix(tid);
            SaasParameter.setTenant(tenantVo);
        } catch (Exception e) {
            log.error("===异常信息===", e);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {}
}
